14. Setup a ViewModel Test
L5 P2 A03 Setup A ViewModel Test V2
As you just saw in the video, you'll start writing a test for the addNewTask method in the TasksViewModel:
TasksViewModel.kt
fun addNewTask() {
_newTaskEvent.value = Event(Unit)
}
Step 1: Make A TaskViewModelTest class
Following the same steps you did for StatisticsUtilTest, create a test file for TasksViewModelTest:
- Open up the class you wish to test, in the tasks package,
TasksViewModel. - Right click on the class name
TasksViewModel-> Generate -> Test. - On the Create Test screen, click OK to accept (no need to change any of the default settings).
- On the Choose Destination Directory dialog, choose the test directory.
Step 2: Start Writing the Test
- Create a new test called
addNewTask_setsNewTaskEvent:
TasksViewModelTest.kt
class TasksViewModelTest {
@Test
fun addNewTask_setsNewTaskEvent() {
// Given a fresh TasksViewModel
// When adding a new task
// Then the new task event is triggered
}
}
Step 3: Use AndroidX Test to get a simulated Android Context
- Add the AndroidX test dependencies.
- Add the Robolectric dependency.
app/build.gradle
dependencies {
// Other dependencies
// AndroidX Test - JVM testing
testImplementation "androidx.test:core-ktx:$androidXTestCoreVersion"
testImplementation "org.robolectric:robolectric:$robolectricVersion"
"androidx.test.ext:junit-ktx:$androidXTestExtKotlinRunnerVersion"
}
- Create a
TasksViewModelusingApplicationProvider.getApplicationContext()from theAndroidXtest library:
TasksViewModelTest.kt
@Test
fun addNewTask_setsNewTaskEvent() {
// Given a fresh ViewModel
val tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())
// When adding a new task
tasksViewModel.addNewTask()
// Then the new task event is triggered
// TODO test LiveData
}
- Add the AndoirdJUnit4 test runner:
TasksViewModelTest.kt
@RunWith(AndroidJUnit4::class)
class TasksViewModelTest {
@Test
fun addNewTask_setsNewTaskEvent() {
// Given a fresh ViewModel
val tasksViewModel = TasksViewModel(ApplicationProvider.getApplicationContext())
// When adding a new task
tasksViewModel.addNewTask()
// Then the new task event is triggered
// TODO test LiveData
}
}
- Run your
TasksViewModelTest. It should pass. In the output, you'll see Robolectric is running your tests: